package com.app.bimo.library_db.helper;


import android.util.Log;

import com.app.bimo.library_db.UserData;
import com.app.bimo.library_db.dao.DaoSession;
import com.app.bimo.library_db.dao.UserDataDao;
import com.app.bimo.library_db.helper.DaoDbHelper;

public class UserHelper {

    private static volatile UserHelper sInstance;
    private static DaoSession daoSession;
    private static UserDataDao userBeanDao;
    private static boolean isChange = true;
    private static UserData userData;

    public static UserHelper getsInstance() {
        if (sInstance == null) {
            synchronized (UserHelper.class) {
                if (sInstance == null) {
                    sInstance = new UserHelper();
                    daoSession = DaoDbHelper.getInstance().getSession();
                    userBeanDao = daoSession.getUserDataDao();
                }
            }
        }
        return sInstance;
    }


    public void saveUser(UserData userBean) {
        userBeanDao.insertOrReplace(userBean);
        userBeanDao.detachAll();
        isChange = true;
    }



    public void updateUser(UserData userBean) {
        userBeanDao.update(userBean);
        userBeanDao.detachAll();
        isChange = true;
    }


    public void removeUser() {
        userBeanDao.deleteAll();
        isChange = true;
    }


    public UserData findUserNickname(String nickname) {
        return userBeanDao.queryBuilder().where(UserDataDao.Properties.Nickname.eq(nickname)).unique() != null
                ? userBeanDao.queryBuilder().where(UserDataDao.Properties.Nickname.eq(nickname)).unique() : null;
    }



    public UserData findUser() {
        if (!isChange) return userData;
        if (userBeanDao.queryBuilder().count() != 0){
            userData = userBeanDao.queryBuilder().list().get(0);
        }else{
            userData = null;
        }
        isChange = false;
        return userData;
    }

}
